package com.instpower.things.handlers;

import com.instpower.things.config.CmdEnum;
import com.instpower.things.config.Configs;
import com.instpower.things.entity.CabinetCmdLog;
import com.instpower.things.instpower.Connection;
import com.instpower.things.instpower.Handler;
import com.instpower.things.transport.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @ClassName Handler08A6Action
 * @Author: hellmash@gmail.com
 * @Date: 2020/6/9
 * @Version: 1.0.0
 * @Description: 机器重启
 */
@Component(value = "CMD08A6")
public class Handler08A6Action extends Handler<Request> {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public short getId() {
        return Configs.REBOOT_CMD;
    }

    @Override
    public void execute(Connection connection, Request request) throws UnsupportedEncodingException {
        byte[] result = request.getData().getDatas();
        CabinetCmdLog cmdLog = new CabinetCmdLog();
        String addr = request.getHeader().getAddr();

        logger.info("[{}]:Exec - CMD08A6 - BEGIN",addr);

        cmdLog.setCabinetSn(addr);
        cmdLog.setCabinetCmd(CmdEnum.REBOOT);
        cmdLog.setCmdCode(String.format("0x%02x", Configs.REBOOT_CMD));
        if(0 == result[0]){
            logger.debug("[{}]重启成功",addr);
            cmdLog.setCabinetLog("机柜重启成功!");
        }else {
            cmdLog.setCabinetLog("机柜重启失败!");
            logger.debug("[{}]重启失败",addr);
        }
        String sessionKey = String.format(Configs.CMD_REBOOT_KEY_PREF, cmdLog.getCabinetSn());
        String sessionId = redisTemplate.opsForValue().get(sessionKey);
        if(sessionId != null) {
            cmdLog.setSessionId(sessionId);
        }
        instService.logCabinetCmd(cmdLog);
        logger.info("[{}]:Exec - CMD08A6 - END",addr);
    }
}
